async function getDHash(imageUrl) {
	return new Promise((resolve, reject) => {
		const img = new Image();
		img.crossOrigin = 'anonymous';
		img.src = imageUrl;

		img.onload = () => {
			const canvas = document.createElement('canvas');
			const ctx = canvas.getContext('2d');

			// 调整图片大小为 9x8
			const width = 9;
			const height = 8;
			canvas.width = width;
			canvas.height = height;
			ctx.drawImage(img, 0, 0, width, height);

			// 获取像素数据
			const imageData = ctx.getImageData(0, 0, width, height);
			const data = imageData.data;

			// 灰度化
			const grayscale = [];
			for (let i = 0; i < data.length; i += 4) {
				const r = data[i];
				const g = data[i + 1];
				const b = data[i + 2];
				const gray = (r + g + b) / 3;
				grayscale.push(gray);
			}

			// 计算 dHash
			let hash = '';
			for (let y = 0; y < height; y++) {
				for (let x = 0; x < width - 1; x++) {
					const index = y * width + x;
					hash += grayscale[index] < grayscale[index + 1] ? '1' : '0';
				}
			}

			resolve(hash);
		};

		img.onerror = () => {
			reject(new Error('Failed to load image'));
		};
	});
}

// 计算两个哈希值的汉明距离
function hammingDistance(hash1, hash2) {
	let distance = 0;
	for (let i = 0; i < hash1.length; i++) {
		if (hash1[i] !== hash2[i]) {
			distance++;
		}
	}
	return distance;
}

// 比对当前凭证哈希值与历史记录中的哈希值
async function compareWithHistory(imageUrl, historyHashes, threshold1) {
	console.log(imageUrl);
	console.log(historyHashes);
	console.log(threshold1);
	try {
		const currentHash = await getDHash(imageUrl);
		console.log("currentHash", currentHash);

		const threshold = threshold1; // 90% 相似度对应的汉明距离阈值
		console.log("threshold", threshold);
		for (let i = 0; i < historyHashes.length; i++) {
			const historyHash = historyHashes[i];
			const distance = hammingDistance(currentHash, historyHash);
			if (distance <= threshold) {
				return {
					currentHash: currentHash,
					isSame: true
				}; // 相似度达到 90% 以上
			}
		}
		return {
			currentHash: currentHash,
			isSame: false
		};;
	} catch (error) {
		console.error('Error calculating hash:', error);
		return false;
	}
}
export default compareWithHistory